package com.gz.controller;

import com.alibaba.fastjson.JSON;
import com.gz.common.Constant;
import com.gz.common.CustomerService;
import com.gz.common.model.Customer;
import com.gz.interceptor.TokenInterceptor;
import com.gz.utils.*;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.upload.UploadFile;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 客户接口
 */
public class CustomerController extends Controller {

    //登录
    public void login() {
        String account = getPara("account");
        String password = getPara("password");
        if (StringUtil.isEmpty(account)) {
            renderJson(Response.responseJson(201, "请输入手机号"));
            return;
        }
        if (StringUtil.isEmpty(password)) {
            renderJson(Response.responseJson(202, "请输入密码"));
            return;
        }

        Customer customer = CustomerService.getService().getCustomerByAccount(account);
        if (customer == null) {
            renderJson(Response.responseJson(404, "用户不存在"));
            return;
        }
        if (customer != null && customer.getPassword().equals(password)) {
            Map<String, String> loginInfo = new HashMap<>();
            String token = MD5.MD5Encode(customer.getMobile() + customer.getUsername());
            loginInfo.put("token", token);
            loginInfo.put("discountUrl", "http://hxms.dbwspt.com/index.php?r=s/p&i=a1e0a4");
            loginInfo.put("homeUrl", "https://www.haximeishi.com/#/?token=" + token);
            loginInfo.put("shopUrl", "http://shop.haximeishi.com:85/shop/home.html");
            loginInfo.put("nickName", customer.getNickname());
            Redis.use("cms").setex(token, 60 * 60, JSON.toJSONString(customer));
            renderJson(Response.responseJson(200, "登录成功", loginInfo));
            return;
        } else {
            renderJson(Response.responseJson(203, "用户名或密码错误"));
            return;
        }
    }

    //注销
    @Before(TokenInterceptor.class)
    public void logout() {
        try {
            String token = this.getAttr("token");
            Redis.use("cms").decr(token);
            renderJson(Response.responseJson(200, "成功"));
            return;

        } catch (Exception e) {
            renderJson(Response.responseJson(500, "系统异常"));
            return;
        }
    }

    //注册
    public void register() {
        try {
            String jsonStr = HttpKit.readData(getRequest());
            if (StringUtil.isEmpty(jsonStr)) {
                renderJson(Response.responseJson(201, "请输入注册信息"));
                return;
            }
            Map<String, String> regisMap = JSON.parseObject(jsonStr, Map.class);
            String nikeName = regisMap.get("nikeName");
            String mobile = regisMap.get("mobile");
            String password = regisMap.get("password");
            String code = regisMap.get("code");
            String captcha = regisMap.get("captcha");
            if (StringUtil.isEmpty(nikeName)) {
                renderJson(Response.responseJson(202, "请输入昵称"));
                return;
            }
            if (StringUtil.isEmpty(mobile)) {
                renderJson(Response.responseJson(203, "请输入手机号"));
                return;
            }
            if (StringUtil.isEmpty(password)) {
                renderJson(Response.responseJson(204, "请输入密码"));
                return;
            }

            if (StringUtil.isEmpty(code)) {
                renderJson(Response.responseJson(205, "请输入正确的激活码"));
                return;
            }
            String validateCaptcha = Redis.use("cms").get(mobile + "_captcha");
            if (StringUtil.isEmpty(captcha) || !captcha.equals(validateCaptcha)) {
                renderJson(Response.responseJson(206, "验证码已过期或不正确"));
                return;
            }
            Customer customer = CustomerService.getService().getCustomerByAccount(mobile);
            if (customer != null) {
                renderJson(Response.responseJson(207, "用户已经存在"));
                return;
            }
            customer = new Customer();
            customer.setNickname(nikeName);
            customer.setMobile(mobile);
            customer.setPassword(password);
            customer.setCode(Integer.valueOf(code));
            customer.setActivated(new Date());
            Boolean result = customer.save();
            if (result) {
                renderJson(Response.responseJson(200, "注册成功"));
                return;
            } else {
                renderJson(Response.responseJson(501, "注册失败"));
                return;
            }
        } catch (Exception e) {
            renderJson(Response.responseJson(500, "系统异常", e.getMessage()));
            return;
        }
    }

    //修改密码
    public void modifyPassword() {
        try {
            String jsonStr = HttpKit.readData(getRequest());
            if (StringUtil.isEmpty(jsonStr)) {
                renderJson(Response.responseJson(201, "输入信息有误"));
                return;
            }
            Map<String, String> regisMap = JSON.parseObject(jsonStr, Map.class);
            String mobile = regisMap.get("mobile");
            String password = regisMap.get("password");
            String captcha = regisMap.get("captcha");
            if (StringUtil.isEmpty(mobile)) {
                renderJson(Response.responseJson(203, "请输入手机号"));
                return;
            }
            if (StringUtil.isEmpty(password)) {
                renderJson(Response.responseJson(204, "请输入密码"));
                return;
            }
            String validateCaptcha = Redis.use("cms").get(mobile + "_captcha");
            if (StringUtil.isEmpty(captcha) || !captcha.equals(validateCaptcha)) {
                renderJson(Response.responseJson(206, "验证码已过期或不正确"));
                return;
            }
            Customer customer = CustomerService.getService().getCustomerByAccount(mobile);
            if (customer == null) {
                renderJson(Response.responseJson(404, "用户不存在"));
                return;
            }
            customer.setPassword(password);
            if (customer.update()) {
                renderJson(Response.responseJson(200, "修改密码成功"));
                return;
            } else {
                renderJson(Response.responseJson(501, "修改密码失败"));
                return;
            }
        } catch (Exception e) {
            renderJson(Response.responseJson(500, "系统异常"));
            return;
        }
    }

    //修改激活码
    @Before(TokenInterceptor.class)
    public void modifyCode() {
        try {
            Customer customer = this.getAttr("customer");
            String jsonStr = HttpKit.readData(getRequest());
            if (StringUtil.isEmpty(jsonStr)) {
                renderJson(Response.responseJson(203, "激活码信息有误"));
                return;
            }
            Map<String, String> regisMap = JSON.parseObject(jsonStr, Map.class);
            //TODO 需要验证激活码的合法性
            String code = regisMap.get("code");
            if (StringUtil.isEmpty(code)) {
                renderJson(Response.responseJson(203, "激活码信息有误"));
                return;
            }
            customer = CustomerService.getService().getCustomerByAccount(customer.getMobile());
            if (customer == null) {
                renderJson(Response.responseJson(404, "用户不存在"));
                return;
            }
            customer.setCode(Integer.valueOf(code));
            if (customer.update()) {
                renderJson(Response.responseJson(200, "修改成功"));
                return;
            } else {
                renderJson(Response.responseJson(501, "修改失败"));
                return;
            }
        } catch (Exception e) {
            renderJson(Response.responseJson(500, "系统异常"));
            return;
        }
    }

    //修改昵称
    @Before(TokenInterceptor.class)
    public void modifyNikeName() {
        try {
            Customer customer = this.getAttr("customer");
            String jsonStr = HttpKit.readData(getRequest());
            if (StringUtil.isEmpty(jsonStr)) {
                renderJson(Response.responseJson(203, "请输入昵称"));
                return;
            }
            Map<String, String> regisMap = JSON.parseObject(jsonStr, Map.class);
            String nikeName = regisMap.get("nikeName");
            if (StringUtil.isEmpty(nikeName)) {
                renderJson(Response.responseJson(203, "请输入昵称"));
                return;
            }
            customer = CustomerService.getService().getCustomerByAccount(customer.getMobile());
            if (customer == null) {
                renderJson(Response.responseJson(404, "用户不存在"));
                return;
            }
            customer.setNickname(nikeName);
            if (customer.update()) {
                renderJson(Response.responseJson(200, "修改成功"));
                return;
            } else {
                renderJson(Response.responseJson(501, "修改失败"));
                return;
            }
        } catch (Exception e) {
            renderJson(Response.responseJson(500, "系统异常"));
            return;
        }
    }

    //修改性别
    @Before(TokenInterceptor.class)
    public void modifyGender() {
        try {
            Customer customer = this.getAttr("customer");
            String jsonStr = HttpKit.readData(getRequest());
            if (StringUtil.isEmpty(jsonStr)) {
                renderJson(Response.responseJson(203, "请输入性别"));
                return;
            }
            Map<String, String> regisMap = JSON.parseObject(jsonStr, Map.class);
            String gender = regisMap.get("gender");
            if (StringUtil.isEmpty(gender)) {
                renderJson(Response.responseJson(203, "请输入性别"));
                return;
            }
            customer = CustomerService.getService().getCustomerByAccount(customer.getMobile());
            if (customer == null) {
                renderJson(Response.responseJson(404, "用户不存在"));
                return;
            }
            customer.setGender(gender);
            if (customer.update()) {
                renderJson(Response.responseJson(200, "修改成功"));
                return;
            } else {
                renderJson(Response.responseJson(501, "修改失败"));
                return;
            }
        } catch (Exception e) {
            renderJson(Response.responseJson(500, "系统异常"));
            return;
        }
    }

    //个人信息
    @Before(TokenInterceptor.class)
    public void detail() {
        try {
            Customer customer = this.getAttr("customer");
            customer = CustomerService.getService().getCustomerByAccount(customer.getMobile());
            if (customer == null) {
                renderJson(Response.responseJson(404, "用户不存在"));
                return;
            }
            Map<String, Object> customerInfo = new HashMap<>();
            customerInfo.put("nikeName", customer.getNickname());
            customerInfo.put("gender", customer.getGender());
            customerInfo.put("image", Constant.API_HOST_PATH + customer.getMobile() + ".jpg");
            customerInfo.put("mobile", customer.getMobile());
            renderJson(Response.responseJson(200, "成功", customerInfo));
            return;
        } catch (Exception e) {
            renderJson(Response.responseJson(500, "系统异常"));
            return;
        }
    }

    //更改头像
    @Before(TokenInterceptor.class)
    public void upload() {
        try {
            Customer customer = this.getAttr("customer");
            UploadFile file = getFile("file", "\\temp");
            if (file == null) {
                renderJson(Response.responseJson(405, "没有发现文件"));
                return;

            }
            customer = CustomerService.getService().getCustomerByAccount(customer.getMobile());
            if (customer == null) {
                renderJson(Response.responseJson(404, "用户不存在"));
                return;
            }
            Map<String, Object> result = CustomerFileUtil.upload(file, customer.getMobile());
            if ((int) result.get("code") == 0) {
                customer.setImage(result.get("url").toString());
                Map<String, String> data = new HashMap<>();
                data.put("image", Constant.API_HOST_PATH + customer.getMobile() + FileUtil.generateWord() + ".jpg");
                if (customer.update()) {
                    renderJson(Response.responseJson(200, "成功", data));
                    return;
                } else {
                    renderJson(Response.responseJson(501, "更改失败"));
                    return;
                }

            } else {
                renderJson(Response.responseJson(501, "更改失败"));
                return;
            }
        } catch (Exception e) {
            renderJson(Response.responseJson(500, "系统异常"));
            return;
        }
    }

    //获取验证码
    public void getCaptcha() {
        try {
            String mobile = getPara("mobile");
            if (StringUtil.isEmpty(mobile)) {
                renderJson(Response.responseJson(501, "手机号码不能为空"));
            } else {
                String captcha = Random.getFourRandom();
                Sms.send(mobile, captcha);
                Redis.use("cms").setex(mobile + "_captcha", 120, captcha);
                renderJson(Response.responseJson(200, "成功"));
            }
        } catch (Exception e) {
            renderJson(Response.responseJson(500, "系统异常"));
        } finally {
            return;
        }
    }


}
